#include<fcntl.h>
#include<unistd.h>
#include<stdio.h>
#include<stdlib.h>
#include<inttypes.h>
int main(int argc, char *argv[])
{
  int fpin,fpout,blocki,blockj,i,j,k,l;
  off_t res;
  off_t filesize;
  uint8_t *pkd_data;
  uint8_t *yuv_data;
  if(argc < 3)
  {
    printf("please use %s file.yuv file.pkd\n", argv[0]);
    return 1;
  }
  fpin = open(argv[1], O_RDONLY);
  if(fpin < 0)
  {
    printf("file %s could not be opened\n", argv[1]);
    return 2;
  }
  filesize = lseek(fpin, 0L, SEEK_END);
  if(filesize < 0)
  {
    perror("fseek1");
    return 3;
  }
  res = lseek(fpin, (off_t)0, SEEK_SET);
  if(res < 0)
  {
    perror("fseek2");
    return 4;
  }

  printf("inputfile has %0ld bytes\n", filesize);
  if(filesize == (307200+153600))
  {
    fpout = open(argv[2], O_CREAT|O_TRUNC|O_WRONLY,S_IRUSR|S_IWUSR);
    if(fpout < 0)
    {
      printf("file %s could not be opened\n", argv[2]);
      return 2;
    }
    yuv_data = malloc(307200+153600);
    pkd_data = malloc(307200+153600);
    if((pkd_data == NULL)||(yuv_data == NULL))
    {
      fprintf(stderr,"problem at malloc\n");
      return 5;
    }
    if(read(fpin, yuv_data,(307200+153600))<0)
    {
      perror("read img_data");
      return 5;
    }
    for(blockj=0;blockj<30;blockj++)
      for(blocki=0;blocki<40;blocki++)
      {
        //4 luma blocks
        for(l=0;l<2;l++)
          for(k=0;k<2;k++)
          {
            for(j=0;j<7;j++)
              for(i=0;i<7;i++)
              {
                pkd_data[(blockj*40+blocki)*(6*64)+(l*2+k)*64+j*8+i] = yuv_data[(blockj*40)*4*64+(l+j)*640+(blocki*2+k)*8+i];
              }
          }
        //1 cb block
        for(j=0;j<7;j++)
          for(i=0;i<7;i++)
          {
            pkd_data[(blockj*40+blocki)*(6*64)+4*64+j*8+i] = yuv_data[307200+(blockj*40)*64+j*320+blocki*8+i];
          }
        //1 cr block
        for(j=0;j<7;j++)
          for(i=0;i<7;i++)
          {
            pkd_data[(blockj*40+blocki)*(6*64)+5*64+j*8+i] = yuv_data[307200+76800+(blockj*40)*64+j*320+blocki*8+i];
          }
          
      }
    if(write(fpout, pkd_data, (307200+153600))<0)
    {
      perror("write");
      return 5;
    }
  }
  close(fpin);
  return 0;
}
